package falcon.server;

import falcon.common.FalconConfig;
import falcon.common.Log;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public final class FalconServer {
	
	public FalconServer(FalconConfig config) {
		m_host = "0.0.0.0";
		m_port = config.getPort();
		m_manager = new FalconProManager(config);
	}
	
	public String getHost() {
		return m_host;
	}
	
	public int getPort() {
		return m_port;
	}
	
	public void run() {
		String host = getHost();
		int port = getPort();

		EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap boot = new ServerBootstrap();
            boot.group(group);
            boot.channel(NioServerSocketChannel.class);
            boot.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel channel) throws Exception {
					ChannelPipeline pipeline = channel.pipeline();
					pipeline.addLast(new FalconByteBufHandler(m_manager));
				}
			});
			try {
				ChannelFuture future = boot.bind(host, port).sync();
				future.channel().closeFuture().sync();
			} catch (Exception e) {
				Log.log(e,  "catch Exception;host=%s;port=%d", m_host, m_port);
			}
        } finally {
        	group.shutdownGracefully();
        }
	}
	
	private String m_host;
	private int m_port;
	private FalconProManager m_manager;
}